<?php
namespace App\Repos;
use App\Models\Cate;
use App\Models\Product;


use App\Models\ProductSale;

use App\Models\AdminHandlerLog;
use Carbon\Carbon;
use DB;
use App\Events\AdminHanderEvent;

class ProductSaleRepo 
{
    
    public static function create($data)
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($data) {              

               
               
                $product = ProductSale::create($data);
                
               

               
                
            });
            $rs['status'] = true;    
            return $rs;
               
            
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    } 

    public static function update($id,$data,$tags=[],$pics=[],$group=[])
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($id,$data,$tags,$pics,$group) {
               
              
                $product = Product::where(['id'=>$id])->update($data);
                $where['product_id'] = $id;
              


                
            });
            $rs['status'] = true;    
            return $rs;
            
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    }   
  

    public static function pages($where=[],$num=20,$fields=['*']) 
    {
    	$list = ProductSale::with('product')->orderBy('created_at','asc')
        					->paginate($num);
        return $list;					
    }

    public static  function destroy($cate_id)
    {
        $rs['status'] = false;
        $productNum = Product::where('cate_id',$cate_id)->count();
        if($productNum>0) {
            $rs['msg'] = '分类下还有商品，所以不能删除';
            return $rs;
        }

        $flag = Cate::destroy($cate_id);
        if($flag) {
            $rs['status'] = true;
        }
        return $rs;


    }

   public static function getRec()
   {
        return ProductSale::where('status',1)
                            ->with('product:id,thumb')
                            ->orderBy('id','desc')
                            ->first();
   }



    // 修改产品上下架状态
    public static function ChangeStatus($id,$data)
    {
        $updateData['on_sale'] = $data['status'];
        self::update(['id'=>$id],$updateData);
        AdminHandlerLogRepo::create('Product',$id,$data);
        //dd($adminHandlerLog);       
        //event(new AdminHanderEvent($adminHandlerLog));

    }
}
